package cn.cvs.web;

import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SupplierService;
import cn.cvs.util.Constants;
import cn.cvs.util.PageSupport;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class SupplierController {
    @Resource
    SupplierService supplierService;

    /**
     * 查询供应商列表
     */
    @RequestMapping("/sys/supplier/list")
    public String supplierList(@RequestParam(value = "querySupCode",required = false) String supCode,
                               @RequestParam(value = "querySupName",required = false) String supName,
                               @RequestParam(value = "pageIndex",required = false,defaultValue = "1") Integer pageNo,
                               Model model){
        //querySupCode 供应商编码
        model.addAttribute("querySupCode",supCode);
        //querySupName 供应商名称
        model.addAttribute("querySupName",supName);
        //supplierList 供应商信息列表*
        List<Supplier> suppliers = supplierService.querySupplierPage(supCode, supName, pageNo, Constants.pageSize);
        model.addAttribute("supplierList",suppliers);
        //totalCount 查询出的总记录数*
        int count = supplierService.querySupplierCount(supCode, supName);
        model.addAttribute("totalCount",count);
        //currentPageNo 当前页码
        model.addAttribute("currentPageNo",pageNo);
        //totalPageCount 总页数
        PageSupport pageSupport = new PageSupport();
        pageSupport.setPageSize(Constants.pageSize);
        pageSupport.setTotalCount(count);
        int totalPageCount = pageSupport.getTotalPageCount();
        model.addAttribute("totalPageCount",totalPageCount);
        return "supplier/list";
    }

    /**
     * 同步
     * 查看指定用户信息
     * @return
     */
    @RequestMapping("/sys/supplier/view/{id}")
    public String supplierList(@PathVariable(value = "id") Integer supId,
                               Model model){
        Supplier supplier = supplierService.queryByIdAndNameSupplier(supId);
        model.addAttribute("supplier",supplier);
        return "supplier/view";
    }

    /**
     * 跳转修改供应商页面
     */
    @RequestMapping("sys/supplier/toUpdate/{id}")
    public String toUpdate(@PathVariable("id") Integer id, Model model){
        Supplier supplier = supplierService.queryByIdAndNameSupplier(id);
        model.addAttribute("supplier",supplier);
        return "supplier/update";
    }

    /**
     * 修改用户
     */
    @PostMapping("/supplier/update")
    public String update(@Valid Supplier supplier, BindingResult bindingResult, HttpSession session){
        SysUser attribute = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (attribute==null){
            throw new RuntimeException("请登录后操作");
        }

        //效验后台数据
        if (bindingResult.hasErrors()) {
            return "supplier/update";
        }

        supplier.setUpdatedTime(new Date());
        supplier.setUpdatedUserId(attribute.getId());
        int i = supplierService.updateSupplier(supplier);
        if(i>0){
            return "redirect:/sys/supplier/list";
        }else{
            throw new RuntimeException("修改供应商信息失败");
        }
    }

    /**
     * 跳转供应商添加页面
     */
    @RequestMapping("sys/supplier/toAdd")
    public String toAdd(@ModelAttribute("supplier") Supplier supplier){
        return "supplier/add";
    }

    /**
     * 添加供应商
     */
    @PostMapping("/sys/supplier/add")
    public String addSup(@Valid Supplier supplier, BindingResult bindingResult,
                         HttpSession session,
                         @RequestParam(value = "attaches",required = false) MultipartFile[] attaches,
                         HttpServletRequest request){

        SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
        if (sysUser==null){
            throw new RuntimeException("请登录后操作");
        }

        //效验后台数据
        if (bindingResult.hasErrors()) {
            throw new RuntimeException("数据效验错误");
            //return "supplier/add";
        }

        for (int i = 0; i < attaches.length; i++) {
            //时间戳
            String saveFileName=System.currentTimeMillis()+"_"+attaches[i].getOriginalFilename();
            //保存到服务器上的路径
            String dirPath=
                    request.getSession().getServletContext().getRealPath("statics"+ File.separator +"uploadFiles");
            //生成路径
            File dir=new File(dirPath);
            if (!dir.exists()) {
                //如果这个目录不存在就创建
                dir.mkdirs();
            }
            File saveFile=new File(dir,saveFileName);//将saveFileName这个文件放入到dir目录中
            try {
                attaches[i].transferTo(saveFile);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("图片上传失败",e);
            }
            //保存一个逻辑路径,方便在其他地方引用
            String picPath=File.separator+"statics"+File.separator+"uploadFiles"+File.separator+saveFileName;
            if(i==0){
                //企业营业执照
                supplier.setCompanyLicPic(picPath);
            }else{
                //组织机构代码证
                supplier.setOrgCodePic(picPath);
            }
        }

        supplier.setCreatedTime(new Date());
        supplier.setCreatedUserId(sysUser.getId());
        int i = supplierService.insertSupplier(supplier);
        if (i>0) {
            return "redirect:/sys/supplier/list";
        }else{
            throw new RuntimeException("添加供应商失败");
        }
    }

    /**
     * 删除供货商
     */
    @ResponseBody
    @DeleteMapping("/sys/supplier/del/{uid}")
    public Object deleteSupper(@PathVariable("uid") Integer id, HttpServletRequest request, HttpSession session){
        //返回值对象
        Map<String,Object> resultMap=new HashMap<String,Object>();
        try {
            SysUser sysUser = (SysUser) session.getAttribute(Constants.USER_SESSION);
            //登录检查
            if (sysUser==null) {
                resultMap.put("delResult","noLogin");
                resultMap.put("msg","请登录后操作");
                return JSON.toJSONString(resultMap);
            }
            //参数非空判断
            if (id==null) {
                resultMap.put("delResult","error");
                resultMap.put("msg","参数错误");
                return JSON.toJSONString(resultMap);
            }
            //非管理员不能删除
            if (sysUser.getRoleId()!=1) {
                resultMap.put("delResult","notadmin");
                resultMap.put("msg","非管理员不能删除");
                return JSON.toJSONString(resultMap);
            }
            //查询该供货商下是否还有订单
            int count = supplierService.queryByIdPayStatus(id);
            System.out.println(count);
            if (count>0) {
                resultMap.put("delResult","also");
                resultMap.put("count",count);
                return JSON.toJSONString(resultMap);
            }else{
                //依据id查询要删除的用户
                int deleteSupplier = supplierService.deleteSupplier(id, request);
                if (deleteSupplier>0) {
                    resultMap.put("delResult","true");
                }else{
                    resultMap.put("delResult","false");
                }
                return JSON.toJSONString(resultMap);
            }
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("delResult","error");
            resultMap.put("msg","系统繁忙,请稍后再试");
            return JSON.toJSONString(resultMap);
        }
    }


}
